package cn.wolfcode.business.serviceItem.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.wolfcode.business.packageAudit.domain.BusCarPackageAudit;
import cn.wolfcode.business.packageAudit.mapper.BusCarPackageAuditMapper;
import cn.wolfcode.business.serviceItem.domain.vo.BusAuditInfo;
import cn.wolfcode.business.serviceItem.domain.vo.BusServiceItemDTO;
import cn.wolfcode.business.serviceItem.domain.vo.BusServiceItemVO;
import cn.wolfcode.common.core.domain.entity.SysUser;
import cn.wolfcode.common.utils.DateUtils;
import cn.wolfcode.common.utils.SecurityUtils;
import cn.wolfcode.system.mapper.SysUserMapper;
import cn.wolfcode.system.service.ISysConfigService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.wolfcode.business.serviceItem.mapper.BusServiceItemMapper;
import cn.wolfcode.business.serviceItem.domain.BusServiceItem;
import cn.wolfcode.business.serviceItem.service.IBusServiceItemService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * 服务项Service业务层处理
 * 
 * @author wolfcode
 * @date 2023-05-31
 */
@Service
@Transactional
public class BusServiceItemServiceImpl implements IBusServiceItemService 
{
    @Autowired
    private BusServiceItemMapper busServiceItemMapper;
    @Autowired
    private BusCarPackageAuditMapper busCarPackageAuditMapper;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ISysConfigService sysConfigService;

    /**
     * 查询服务项
     * 
     * @param id 服务项主键
     * @return 服务项
     */
    @Override
    public BusServiceItem selectBusServiceItemById(Long id)
    {
        return busServiceItemMapper.selectBusServiceItemById(id);
    }

    /**
     * 查询服务项列表
     * 
     * @param busServiceItem 服务项
     * @return 服务项
     */
    @Override
    public List<BusServiceItem> selectBusServiceItemList(BusServiceItem busServiceItem)
    {
        return busServiceItemMapper.selectBusServiceItemList(busServiceItem);
    }

    /**
     * 新增服务项
     * 
     * @param busServiceItemVO 服务项
     * @return 结果
     */
    @Override
    public int insertBusServiceItem(BusServiceItemVO busServiceItemVO)
    {
        if(busServiceItemVO == null){
            throw new RuntimeException("非法操作");
        }
        if(busServiceItemVO.getDiscountPrice().compareTo(busServiceItemVO.getOriginalPrice()) > 0){
            throw new RuntimeException("折扣金额不能大于报价");
        }
        BusServiceItem busServiceItem = new BusServiceItem();
        BeanUtils.copyProperties(busServiceItemVO,busServiceItem);
        if(BusServiceItem.CARPACKAGE_YES.equals(busServiceItem.getCarPackage())){
            busServiceItem.setAuditStatus(BusServiceItem.AUDITSTATUS_INIT);
        } else if (BusServiceItem.CARPACKAGE_NO.equals(busServiceItem.getCarPackage())){
            busServiceItem.setAuditStatus(BusServiceItem.AUDITSTATUS_NO_REQUIRED);
        } else {
            throw new RuntimeException("非法操作");
        }
        busServiceItem.setCreateTime(DateUtils.getNowDate());
        return busServiceItemMapper.insertBusServiceItem(busServiceItem);
    }

    /**
     * 修改服务项
     * 
     * @param busServiceItemVO 服务项
     * @return 结果
     */
    @Override
    public int updateBusServiceItem(BusServiceItemVO busServiceItemVO)
    {
        if(busServiceItemVO == null){
            throw new RuntimeException("非法操作");
        }
        if(busServiceItemVO.getDiscountPrice().compareTo(busServiceItemVO.getOriginalPrice()) > 0){
            throw new RuntimeException("折扣金额不能大于报价");
        }
        BusServiceItem busServiceItem = busServiceItemMapper.selectBusServiceItemById(busServiceItemVO.getId());
        if(busServiceItem == null){
            throw new RuntimeException("非法操作");
        }
        if(BusServiceItem.AUDITSTATUS_AUDITING.equals(busServiceItem.getAuditStatus()) ||
                BusServiceItem.AUDITSTATUS_APPROVED.equals(busServiceItem.getAuditStatus()) ||
                BusServiceItem.SALESTATUS_ON.equals(busServiceItem.getSaleStatus())){
            throw new RuntimeException("状态不合法");
        }
        BeanUtils.copyProperties(busServiceItemVO,busServiceItem);
        if(BusServiceItem.CARPACKAGE_YES.equals(busServiceItem.getCarPackage())){
            busServiceItem.setAuditStatus(BusServiceItem.AUDITSTATUS_INIT);
        }
        return busServiceItemMapper.updateBusServiceItem(busServiceItem);
    }

    /**
     * 批量删除服务项
     *
     * @param ids 需要删除的服务项主键
     * @return 结果
     */
    @Override
    public int deleteBusServiceItemByIds(Long[] ids)
    {
        return busServiceItemMapper.deleteBusServiceItemByIds(ids);
    }

    /**
     * 删除服务项信息
     *
     * @param id 服务项主键
     * @return 结果
     */
    @Override
    public int deleteBusServiceItemById(Long id)
    {
        return busServiceItemMapper.deleteBusServiceItemById(id);
    }

    @Override
    public int saleOn(Long id) {
        if(id == null){
            throw new RuntimeException("非法操作");
        }
        BusServiceItem busServiceItem = busServiceItemMapper.selectBusServiceItemById(id);
        if(busServiceItem == null){
            throw new RuntimeException("非法操作");
        }
        if(!(BusServiceItem.AUDITSTATUS_APPROVED.equals(busServiceItem.getAuditStatus()) ||
                BusServiceItem.AUDITSTATUS_NO_REQUIRED.equals(busServiceItem.getAuditStatus()))){
            throw new RuntimeException("必须要审核通过才能上架");
        }
        if(BusServiceItem.SALESTATUS_ON.equals(busServiceItem.getSaleStatus())){
            throw new RuntimeException("必须要下架状态才能上架");
        }
        return busServiceItemMapper.changeSaleStatus(id,BusServiceItem.SALESTATUS_ON);
    }

    @Override
    public int saleOff(Long id) {
        if(id == null){
            throw new RuntimeException("非法操作");
        }
        BusServiceItem busServiceItem = busServiceItemMapper.selectBusServiceItemById(id);
        if(busServiceItem == null){
            throw new RuntimeException("非法操作");
        }
        if(BusServiceItem.SALESTATUS_OFF.equals(busServiceItem.getSaleStatus())){
            throw new RuntimeException("必须要上架状态才能下架");
        }
        return busServiceItemMapper.changeSaleStatus(id,BusServiceItem.SALESTATUS_OFF);
    }

    @Override
    public BusAuditInfo queryBusAuditInfoByServiceItemId(Long id) {
        Assert.notNull(id,"非法操作");
        BusServiceItem busServiceItem = busServiceItemMapper.selectBusServiceItemById(id);
        Assert.notNull(busServiceItem,"非法操作");
        List<SysUser> shopOwners = sysUserMapper.queryUserByRoleName("店长");

        BusAuditInfo auditInfo = new BusAuditInfo();
        auditInfo.setBusServiceItem(busServiceItem);
        auditInfo.setShopOwners(shopOwners);

        String discountPriceLimit = sysConfigService.selectConfigByKey("discountPriceLimit");
        if(busServiceItem.getDiscountPrice().compareTo(new BigDecimal(discountPriceLimit)) > 0){
            List<SysUser> finances = sysUserMapper.queryUserByRoleName("财务");
            auditInfo.setFinances(finances);
        }
        return auditInfo;
    }

    @Override
    public int startAudit(BusServiceItemDTO dto) {
        Assert.notNull(dto,"非法操作");
        Assert.notNull(dto.getId(),"非法操作");
        Assert.notNull(dto.getShopOwnerId(),"非法操作");

        BusServiceItem busServiceItem = busServiceItemMapper.selectBusServiceItemById(dto.getId());
        Assert.notNull(busServiceItem,"非法操作");
        Assert.state(BusServiceItem.CARPACKAGE_YES.equals(busServiceItem.getCarPackage()),
                "只有套餐可以审核");
        Assert.state(BusServiceItem.AUDITSTATUS_INIT.equals(busServiceItem.getAuditStatus()) ||
                BusServiceItem.AUDITSTATUS_REPLY.equals(busServiceItem.getAuditStatus()),
                "只有初始化状态或重新调整状态才能审核");

        String processDefinitionKey = "bus_car_package";
        Map<String,Object> map = new HashMap<>();
        map.put("shopOwnerId",dto.getShopOwnerId());
        if(dto.getFinanceId() != null){
            map.put("financeId",dto.getFinanceId());
        }
        map.put("disCountPrice",busServiceItem.getDiscountPrice().longValue());
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey,
                busServiceItem.getId().toString(), map);

        BusCarPackageAudit busCarPackageAudit = new BusCarPackageAudit();
        busCarPackageAudit.setServiceItemId(busServiceItem.getId());
        busCarPackageAudit.setServiceItemName(busServiceItem.getName());
        busCarPackageAudit.setServiceItemInfo(busServiceItem.getInfo());
        busCarPackageAudit.setServiceItemPrice(busServiceItem.getDiscountPrice());
        busCarPackageAudit.setInstanceId(processInstance.getProcessInstanceId());
        busCarPackageAudit.setCreatorId(SecurityUtils.getUserId().toString());
        busCarPackageAudit.setCreateBy(SecurityUtils.getUsername());
        busCarPackageAudit.setInfo(dto.getInfo());
        busCarPackageAudit.setStatus(BusCarPackageAudit.STATUS_IN_ROGRESS);
        busCarPackageAudit.setCreateTime(new Date());
        busServiceItemMapper.changeAuditStatus(dto.getId(),BusServiceItem.AUDITSTATUS_AUDITING);
        return busCarPackageAuditMapper.insertBusCarPackageAudit(busCarPackageAudit);
    }
}
